<template>
  <view class="file-list">
    <view class="file" v-for="(item, index) in files" :key="index">
      <view
        v-if="canDownload"
        class="download-btn"
        @click="handleDownload(item.src, item.name || '')"
      >
        <text class="cuIcon-down"></text>
      </view>
      <image
        class="file-item"
        v-if="item.type === 'image'"
        :src="item.src"
        @click="previewImage(item.src)"
        mode="aspectFill"
      ></image>
      <view
        v-else-if="item.type === 'video'"
        class="file-item doc"
        :class="item.type"
        @click="previewVideo(item.src)"
      ></view>
      <view v-else class="file-item doc" :class="item.type" @click="previewOnline(item.src)"></view>
      <view v-if="showName" class="name">{{ item.name }}</view>
    </view>
    <th-add-water ref="addWaterRef" v-if="addWater && showAddWater"></th-add-water>
  </view>
</template>

<script lang="ts" setup name="thPreviewFile">
import { getFileType, previewOnline, downloadFileToLocal } from '@/utils/util';

const props = defineProps({
  files: {
    type: [Object],
    default: () => {
      return [];
    },
  },
  useName: {
    type: Boolean,
    default: false,
  },
  showName: {
    type: Boolean,
    default: true,
  },
  canDownload: {
    type: Boolean,
    default: false,
  },
  addWater: {
    type: Boolean,
    default: false,
  },
});
const showAddWater = ref(true);
const addWaterRef = ref(null);

const previewImage = (current) => {
  const urls = props.files.filter((item) => item.type === 'image').map((item) => item.src);
  uni.previewImage({
    current,
    indicator: 'number',
    urls,
    longPressActions: {
      itemList: ['下载'],
      success: (res) => {
        if (res.tapIndex === 0) {
          const currentImage = urls[res.index];
          if (currentImage) {
            const imageName = (props.files.find((item) => item.src === currentImage) || {}).name;
            handleDownload(currentImage, imageName);
          }
        }
      },
    },
  });
};

const previewVideo = (src) => {
  uni.navigateTo({
    url: `/pages/common/preview-video?src=${encodeURIComponent(src)}`,
    animationType: 'fade-in',
  });
};

// 用来直接预览文件
// const previewFile = (url)=>{
//   const fileType = getFileType(url);

//   if (fileType === 'image') {
//     uni.previewImage({
//       urls: [url],
//       current: url,
//     });
//   } else {
//     previewOnline(url);
//   }
// }

const handleDownload = async (src, name) => {
  uni.showLoading({
    title: '下载中...',
    mask: true,
  });
  const fileName = src.substring(src.lastIndexOf('/') + 1);
  const fileType = fileName.split('.')[1];
  const isImage = ['jpg', 'jpeg', 'png', 'gif'].includes(fileType);
  if (isImage && !props.useName) {
    const fileDir = 'file://storage/emulated/0/';
    const filePath = `Pictures/${fileName}`;
    let res = '';
    if (props.addWater) {
      res = await addWaterRef.value.startCreate(src);
      addWaterRef.value.reset();
      if (!res) {
        uni.hideLoading();
        return;
      }
    }
    uni.saveImageToPhotosAlbum({
      filePath: props.addWater ? res : src,
      success: (res) => {
        // console.log(res)
        uni.showToast({
          icon: 'none',
          mask: false,
          title: '已保存到相册', // 保存路径
          duration: 3000,
        });
      },
      fail() {
        uni.showToast({
          icon: 'none',
          mask: true,
          title: '下载失败，请稍后重试',
        });
      },
      complete() {
        uni.hideLoading();
      },
    });
    // const bitmap = new plus.nativeObj.Bitmap(`image`);
    // bitmap.loadBase64Data(base64, (res) => {
    //   console.log("加载成功", res)
    //   bitmap.save(`${fileDir} + ${filePath}`, { overwrite: true, format: fileType, quality: 100 }, (e) => {
    //     console.log(e.target)
    //     resolve(e.target)
    //   }, (err) => {
    //     console.log(err)
    //     reject(err)
    //   })
    // }, (err) => {
    //   reject(err)
    // })
    return;
  }
  const res = await downloadFileToLocal(src, name).catch((err) => {
    console.log(err);
    uni.hideLoading();
    uni.showToast({
      icon: 'none',
      mask: true,
      title: '下载失败，请稍后重试',
    });
  });
  // plus.runtime.openFile(res); //选择软件打开文件
  // console.log(res)
};
</script>

<style lang="scss" scoped>
.file-list {
  font-size: 0;

  .file {
    display: inline-block;
    width: 200rpx;
    // height: 260rpx;
    box-sizing: content-box;
    padding: 12rpx;
    position: relative;

    .file-item {
      width: 100%;
      height: 200rpx;
      border: 1rpx solid #dedede;
    }

    .name {
      width: 100%;
      overflow: hidden;
      margin-top: 12rpx;
      height: 60rpx;
      white-space: pre-wrap;
      font-size: 22rpx;
    }
    .download-btn {
      width: 52rpx;
      height: 52rpx;
      line-height: 52rpx;
      text-align: center;
      border-radius: 4rpx;
      position: absolute;
      top: 12rpx;
      right: 12rpx;
      z-index: 2;
      background-color: rgba(0, 0, 0, 0.3);
      .cuIcon-down {
        font-size: 36rpx;
        color: #fff;
      }
    }
  }

  .doc {
    width: 100%;
    height: 100%;
    display: inline-block;
    border: 1rpx solid #dedede;
  }

  .doc.doc,
  .doc.docx,
  .doc.DOC,
  .doc.DOCX {
    background: url('/static/word.png') no-repeat center center;
    background-size: 100rpx 100rpx;
  }

  .doc.txt,
  .doc.TXT {
    background: url('/static/txt.png') no-repeat center center;
    background-size: 100rpx 100rpx;
  }

  .doc.pdf,
  .doc.PDF {
    background: url('/static/pdf.png') no-repeat center center;
    background-size: 100rpx 100rpx;
  }

  .doc.ppt,
  .doc.pptx {
    background: url('/static/ppt.png') no-repeat center center;
    background-size: 100rpx 100rpx;
  }

  .doc.xlsx {
    background: url('/static/excel.png') no-repeat center center;
    background-size: 100rpx 100rpx;
  }

  .doc.image {
    background: url('/static/image.png') no-repeat center center;
    background-size: 100rpx 100rpx;
  }

  .doc.audio {
    background: url('/static/mp3.png') no-repeat center center;
    background-size: 100rpx 100rpx;
  }

  .doc.video {
    background: url('/static/mp4.png') no-repeat center center;
    background-size: 100rpx 100rpx;
  }
}
</style>
